import { useState } from 'react';
import { ChatOpenAI } from '@langchain/openai';
import { Calculator } from "@langchain/community/tools/calculator";
import { initializeAgentExecutorWithOptions } from 'langchain/agents';

export default function ToolsCall() {
  const [input, setInput] = useState('');
  const [output, setOutput] = useState('');
  const [loading, setLoading] = useState(false);

  const handleSubmit = async () => {
    setLoading(true);
    
    try {
      // 初始化模型和工具
      const model = new ChatOpenAI({ 
        modelName: "gpt-3.5-turbo",
        configuration: {
          apiKey: 'xxx',
          baseURL: 'https://xxx'
        },
       });
      const tools = [new Calculator()]; // 使用计算器工具替代SerpAPI
      
      // 创建执行器
      const executor = await initializeAgentExecutorWithOptions(tools, model, {
        agentType: 'zero-shot-react-description',
        verbose: true,
      });
      
      // 执行查询
      const result = await executor.invoke({ input });
      setOutput(result.output);
    } catch (error) {
      console.error(error);
      setOutput('发生错误: ' + error?.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ 
      maxWidth: '800px', 
      margin: '0 auto',
      padding: '20px',
      fontFamily: 'Arial, sans-serif'
    }}>
      <h3 style={{ 
        color: '#333',
        textAlign: 'center',
        marginBottom: '30px'
      }}>LangChain 工具（计算器）调用示例</h3>
      
      <div style={{ 
        display: 'flex',
        gap: '10px',
        marginBottom: '20px'
      }}>
        <input
          style={{
            flex: 1,
            padding: '0 10px',
            border: '1px solid #ddd',
            borderRadius: '4px',
            fontSize: '16px'
          }}
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="输入您的查询"
        />
        <button 
          style={{
            padding: '8px 10px',
            backgroundColor: loading ? '#ccc' : '#1890ff',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: loading ? 'not-allowed' : 'pointer',
            fontSize: '16px'
          }}
          onClick={handleSubmit} 
          disabled={loading}
        >
          {loading ? '处理中...' : '提交'}
        </button>
      </div>
      
      {output && (
        <div style={{
          padding: '20px',
          backgroundColor: '#f5f5f5',
          borderRadius: '4px',
          borderLeft: '4px solid #1890ff'
        }}>
          <h3 style={{ marginTop: 0 }}>结果:</h3>
          <pre style={{
            whiteSpace: 'pre-wrap',
            wordWrap: 'break-word',
            margin: 0
          }}>{output}</pre>
        </div>
      )}
    </div>
  );
}